package controller;

import java.io.IOException;
import java.util.StringTokenizer;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;

import data.Data;


@SuppressWarnings("serial")
public class ActiveServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		
		String path = ((HttpServletRequest)request).getRequestURI();
		
		StringTokenizer st = new StringTokenizer( path,"/");
        int count = st.countTokens(); 
        
        if(count!=2)
        {
        	
        	response.getWriter().println("Bad request : "+request.getRequestURI());
        	response.getWriter().close();
        	return ;
        	
        }

		// skip one token /sites/gooogle.com (remove sites)
		st.nextToken();
		String code_active = st.nextToken();
		if(code_active!=null)
		{
			DBCollection collection = Data.data("users");
			DBObject dbObject = collection.findOne(new BasicDBObject("code_active",code_active));
			if(dbObject!=null)
			{
				dbObject.put("active", "yes");
				collection.save(dbObject);
				request.setAttribute("dbObject", dbObject);
			}
			try {
				request.getRequestDispatcher("/active.jsp").forward(request,response);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
